package com.yz.transfer;

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Supplier;


/**
 * 坐标系转换工具类
 *
 * @author Administrator
 */
public class CoordinateTransferUtils {

    /**
     * 国内坐标边界
     */
    private static final double MIN_LON = 72.004D;
    private static final double MAX_LON = 137.8347D;
    private static final double MIN_LAT = 0.8293D;
    private static final double MAX_LAT = 55.8271D;

    /**
     * PI 圆周率
     */
    private static final double PI = 3.14159265358979324D;

    /**
     * A WGS 长轴半径
     */
    private static final double A = 6378245.0D;

    /**
     * EE WGS 偏心率的平方
     */
    private static final double EE = 0.00669342162296594323D;

    /**
     * 百度墨卡托转换经纬度常量
     */
    private static final double[] BAND = {12890594.86, 8362377.87, 5591021, 3481989.83, 1678043.12, 0d};
    private static final double[][] MC2LL = {
            {
                    1.410526172116255e-8, 0.00000898305509648872, -1.9939833816331,
                    200.9824383106796, -187.2403703815547, 91.6087516669843,
                    -23.38765649603339, 2.57121317296198, -0.03801003308653, 17337981.2,
            },
            {
                    -7.435856389565537e-9, 0.000008983055097726239, -0.78625201886289,
                    96.32687599759846, -1.85204757529826, -59.36935905485877,
                    47.40033549296737, -16.50741931063887, 2.28786674699375, 10260144.86,
            },
            {
                    -3.030883460898826e-8, 0.00000898305509983578, 0.30071316287616,
                    59.74293618442277, 7.357984074871, -25.38371002664745, 13.45380521110908,
                    -3.29883767235584, 0.32710905363475, 6856817.37,
            },
            {
                    -1.981981304930552e-8, 0.000008983055099779535, 0.03278182852591,
                    40.31678527705744, 0.65659298677277, -4.44255534477492, 0.85341911805263,
                    0.12923347998204, -0.04625736007561, 4482777.06,
            },
            {
                    3.09191371068437e-9, 0.000008983055096812155, 0.00006995724062,
                    23.10934304144901, -0.00023663490511, -0.6321817810242, -0.00663494467273,
                    0.03430082397953, -0.00466043876332, 2555164.4,
            },
            {
                    2.890871144776878e-9, 0.000008983055095805407, -3.068298e-8,
                    7.47137025468032, -0.00000353937994, -0.02145144861037, -0.00001234426596,
                    0.00010322952773, -0.00000323890364, 826088.5,
            },
    };

    /**
     * WGS84转换GCJ02核心方法
     *
     * @param fromLon 转换前的经度
     * @param fromLat 转换前的纬度
     * @return 转换后的经纬度map对象
     */
    public static Map<String, Double> wgs84ToGcj02(double fromLon, double fromLat) {
        HashMap<String, Double> transformRes = new HashMap<>(2);
        // 国外坐标不用进行加密
        if (outOfChina(fromLon, fromLat)) {
            transformRes.put("lon", fromLon);
            transformRes.put("lat", fromLat);
            return transformRes;
        }
        // 计算转换后的经纬度坐标
        double dLat = transformLat(fromLon - 105.0, fromLat - 35.0);
        double dLon = transformLon(fromLon - 105.0, fromLat - 35.0);
        double radLat = fromLat / 180.0 * PI;
        double magic = Math.sin(radLat);
        magic = 1 - EE * magic * magic;
        double sqrtMagic = Math.sqrt(magic);
        dLat = (dLat * 180.0) / ((A * (1 - EE)) / (magic * sqrtMagic) * PI);
        dLon = (dLon * 180.0) / (A / sqrtMagic * Math.cos(radLat) * PI);
        double mgLat = fromLat + dLat;
        double mgLon = fromLon + dLon;
        transformRes.put("lon", new BigDecimal(mgLon + "", new MathContext(9, RoundingMode.HALF_UP)).doubleValue());
        transformRes.put("lat", new BigDecimal(mgLat + "", new MathContext(9, RoundingMode.HALF_UP)).doubleValue());

        return transformRes;
    }

    /**
     * GCJ02转换WGS84
     *
     * @param lon 转换前的经度
     * @param lat 转换后的纬度
     * @return 转换后的经纬度map对象
     */
    public static Map<String, Double> gcj02ToWgs84(double lon, double lat) {
        Map<String, Double> transformRes = new HashMap<>(2);
        double longitude = lon * 2 - wgs84ToGcj02(lon, lat).get("lon");
        double latitude = lat * 2 - wgs84ToGcj02(lon, lat).get("lat");
        transformRes.put("lon", longitude);
        transformRes.put("lat", latitude);
        return transformRes;
    }

    /**
     * GCJ02转换BD09
     *
     * @param gcjLng GCL经度坐标
     * @param gcjLat GCL纬度坐标
     */
    public static Map<String, Double> gcj02ToBd09(double gcjLng, double gcjLat) {
        // 计算
        Map<String, Double> transformRes = new HashMap<>(2);
        double z = Math.sqrt(gcjLng * gcjLng + gcjLat * gcjLat) + 0.00002 * Math.sin(gcjLat * PI);
        double theta = Math.atan2(gcjLat, gcjLng) + 0.000003 * Math.cos(gcjLng * PI);
        // 封装
        transformRes.put("lon", z * Math.cos(theta) + 0.0065);
        transformRes.put("lat", z * Math.sin(theta) + 0.006);
        return transformRes;
    }

    /**
     * BD09转换GCJ02
     *
     * @param bdLng 百度经度坐标
     * @param bdLat 百度纬度坐标
     */
    public static Map<String, Double> bd09ToGcj02(double bdLng, double bdLat) {
        // 计算
        Map<String, Double> transformRes = new HashMap<>(2);
        double x = bdLng - 0.0065, y = bdLat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * PI);
        // 封装
        transformRes.put("lon", z * Math.cos(theta));
        transformRes.put("lat", z * Math.sin(theta));
        return transformRes;
    }

    /**
     * WGS84转换GCJ02优化（处理转换前经纬度坐标为null问题）
     *
     * @param fromLon 转换前的经度
     * @param fromLat 转换前的纬度
     * @param toLon   转换后的经度
     * @param toLat   转换后的纬度
     */
    private static void wgs84ToGcj02(Supplier<BigDecimal> fromLon, Supplier<BigDecimal> fromLat, Consumer<BigDecimal> toLon, Consumer<BigDecimal> toLat) {
        wgs84ToGcj02(Optional.ofNullable(fromLon.get()).orElse(BigDecimal.ZERO), Optional.ofNullable(fromLat.get()).orElse(BigDecimal.ZERO), toLon, toLat);
    }

    /**
     * WGS84转换GCJ02优化（处理转换后经纬度坐标）
     *
     * @param fromLon 转换前的经度
     * @param fromLat 转换前的纬度
     * @param toLon   转换后的经度
     * @param toLat   转换后的纬度
     */
    private static void wgs84ToGcj02(BigDecimal fromLon, BigDecimal fromLat, Consumer<BigDecimal> toLon, Consumer<BigDecimal> toLat) {
        final Map<String, Double> transformRes = wgs84ToGcj02(fromLon.doubleValue(), fromLat.doubleValue());
        toLon.accept(new BigDecimal(transformRes.get("lon") + ""));
        toLat.accept(new BigDecimal(transformRes.get("lat") + ""));
    }

    /**
     * 百度墨卡托坐标转百度经纬度坐标
     *
     * @param lon 转换前的经度
     * @param lat 转换前的纬度
     * @return 转换后的经纬度map对象
     */
    public static Map<String, Double> bdMercatorToBd09(double lon, double lat) {
        double[] point = {lon, lat};
        double absLat = Math.abs(lat);
        double[] arr = {};
        for (int i = 0, len = BAND.length; i < len; i++) {
            if (absLat >= BAND[i]) {
                arr = MC2LL[i];
                break;
            }
        }
        return transfer(point, arr);
    }

    /**
     * 百度墨卡托坐标转百度经纬度坐标：
     *
     * @param point 转换前的座标
     * @param arr   转换使用的矩阵
     * @return 转换后的经纬度map对象
     */
    private static Map<String, Double> transfer(double[] point, double[] arr) {
        Map<String, Double> transformRes = new HashMap<>(2);
        double num = Math.abs(point[1]) / arr[9];
        double lon = arr[0] + arr[1] * Math.abs(point[0]);
        double lat = arr[2] +
                arr[3] * num +
                arr[4] * num * num +
                arr[5] * num * num * num +
                arr[6] * num * num * num * num +
                arr[7] * num * num * num * num * num +
                arr[8] * num * num * num * num * num * num;
        lon *= point[0] < 0 ? -1 : 1;
        lat *= point[1] < 0 ? -1 : 1;
        transformRes.put("lon", lon);
        transformRes.put("lat", lat);
        return transformRes;
    }

    /**
     * 坐标是否在国外
     *
     * @param lon 经度
     * @param lat 纬度
     * @return true 国外坐标 false 国内坐标
     */
    private static boolean outOfChina(double lon, double lat) {
        if (lon < MIN_LON || lon > MAX_LON) {
            return true;
        }
        return lat < MIN_LAT || lat > MAX_LAT;
    }

    /**
     * 转换经度坐标
     *
     * @param x 偏移后的经度
     * @param y 偏移后的纬度
     * @return double 转换经度坐标
     */
    private static double transformLat(double x, double y) {
        double transform = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
        transform += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
        transform += (20.0 * Math.sin(y * PI) + 40.0 * Math.sin(y / 3.0 * PI)) * 2.0 / 3.0;
        transform += (160.0 * Math.sin(y / 12.0 * PI) + 320 * Math.sin(y * PI / 30.0)) * 2.0 / 3.0;
        return transform;
    }

    /**
     * 转换纬度坐标
     *
     * @param x 偏移后的经度
     * @param y 偏移后的纬度
     * @return double 转换纬度坐标
     */
    private static double transformLon(double x, double y) {
        double transform = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        transform += (20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0 / 3.0;
        transform += (20.0 * Math.sin(x * PI) + 40.0 * Math.sin(x / 3.0 * PI)) * 2.0 / 3.0;
        transform += (150.0 * Math.sin(x / 12.0 * PI) + 300.0 * Math.sin(x / 30.0 * PI)) * 2.0 / 3.0;
        return transform;
    }

    /**
     * 坐标系转换工具类测试
     *
     * @param args 参数
     */
    public static void main(String[] args) {
        // 转换后的 113.733069118924,34.409617513021
//        double lon = 113.726919D;
//        double lat = 34.410907D;
//        Map<String, Double> transformResult = wgs84ToGcj02(lon, lat);
//        System.out.println("WGS84ToGCJ02 转换前经纬度(" + lon + "," + lat + ") 转换后经纬度(" + transformResult.get("lon") + "," + transformResult.get("lat") + ")");
//
//        double lon2 = 113.733069118924D;
//        double lat2 = 34.4096175D;
//        Map<String, Double> transform2Result = gcj02ToWgs84(lon2, lat2);
//        System.out.println("GCJ02ToWGS84 转换前经纬度(" + lon2 + "," + lat2 + ") 转换后经纬度(" + transform2Result.get("lon") + "," + transform2Result.get("lat") + ")");

        // WGS84ToGCJ02 116.404, 39.915 转换后 [ 116.41024449916938, 39.91640428150164 ]
        double lon3 = 116.404D;
        double lat3 = 39.915D;
        Map<String, Double> transform3Result = wgs84ToGcj02(lon3, lat3);
        System.out.println("WGS84ToGCJ02 转换前经纬度(" + lon3 + "," + lat3 + ") 转换后经纬度(" + transform3Result.get("lon") + "," + transform3Result.get("lat") + ")");

        // GCJ02ToWGS84 116.404, 39.915 转换后 [ 116.39775550083061, 39.91359571849836 ]
        double lon4 = 116.404D;
        double lat4 = 39.915D;
        Map<String, Double> transform4Result = gcj02ToWgs84(lon4, lat4);
        System.out.println("GCJ02ToWGS84 转换前经纬度(" + lon4 + "," + lat4 + ") 转换后经纬度(" + transform4Result.get("lon") + "," + transform4Result.get("lat") + ")");

        // BD09ToGCJ02 116.404, 39.915 转换后 [ 116.39762729119315, 39.90865673957631 ]
        double lon5 = 116.404D;
        double lat5 = 39.915D;
        Map<String, Double> transform5Result = bd09ToGcj02(lon5, lat5);
        System.out.println("BD09ToGCJ02 转换前经纬度(" + lon5 + "," + lat5 + ") 转换后经纬度(" + transform5Result.get("lon") + "," + transform5Result.get("lat") + ")");

        // GCJ02ToBD09 116.404, 39.915 转换后 [ 116.41036949371029, 39.92133699351021 ]
        double lon6 = 116.404D;
        double lat6 = 39.915D;
        Map<String, Double> transform6Result = gcj02ToBd09(lon6, lat6);
        System.out.println("GCJ02ToBD09 转换前经纬度(" + lon6 + "," + lat6 + ") 转换后经纬度(" + transform6Result.get("lon") + "," + transform6Result.get("lat") + ")");

    }


}
